package com.jiangxiaofei.citycloud.activity.recruit;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.blankj.utilcode.util.EmptyUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.jiangxiaofei.citycloud.R;
import com.jiangxiaofei.citycloud.adapter.RetruitLabelAdapter;
import com.jiangxiaofei.citycloud.adapter.RetruitWorkLabelAdapter;
import com.jiangxiaofei.citycloud.base.BaseActivity;
import com.jiangxiaofei.citycloud.bean.DoWorkInfoBean;
import com.jiangxiaofei.citycloud.bean.WorkLabelBean;
import com.jiangxiaofei.citycloud.constants.Constants;
import com.jiangxiaofei.citycloud.constants.StringConstants;
import com.jiangxiaofei.citycloud.event.LabelMessage;
import com.jiangxiaofei.citycloud.event.RefreshMessage;
import com.jiangxiaofei.citycloud.event.WorkLabelMessage;
import com.jiangxiaofei.citycloud.mvp.RecruitConstant;
import com.jiangxiaofei.citycloud.mvp.RecruitPersenter;
import com.jiangxiaofei.citycloud.param.RecruitDoWorkParam;
import com.jiangxiaofei.citycloud.util.DateUtils;
import com.jiangxiaofei.citycloud.view.FullyGridLayoutManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/9/5 0005.
 * 我要干活页面
 */

public class RecruitDoWorkPublishAcitivty extends BaseActivity
        implements View.OnClickListener, RecruitConstant.DoWorkView,
        RecruitConstant.WorkLabelView, RecruitConstant.DoWorkInfoView,
        RecruitConstant.UpdateWorkerInfoView {

    @InjectView(R.id.do_et_title)
    EditText doEtTitle;
    @InjectView(R.id.do_service_location)
    TextView doServiceLocation;
    @InjectView(R.id.do_tv_bengin_date)
    TextView doTvBenginDate;
    @InjectView(R.id.do_tv_end_date)
    TextView doTvEndDate;
    @InjectView(R.id.do_work_btn_pulish)
    Button doWorkBtnPulish;
    @InjectView(R.id.do_recy_work_label)
    RecyclerView recyWorkLabel;
    private List<WorkLabelBean> workList;
    private RetruitWorkLabelAdapter labelAdapter;
    private RecruitConstant.WorkLabelPersenter workLabelPersenter;
    private RecruitConstant.DoWorkPersenter doWorkPersenter;
    private RecruitConstant.DoWorkInfoPersenter doWorkInfoPersenter;
    private RecruitConstant.UpdateWorkerPersenter updateWorkerPersenter;
    private RecruitDoWorkParam doWorkParam;
    private PopupWindow popupSelectCoverage;
    private Button btn_cannel, btn_ok;
    private RecyclerView recyConverage;
    private List<WorkLabelBean> labelList;
    private RetruitLabelAdapter adapter;
    private int userId;
    private String type;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_recruit_do_work_layout);
        ButterKnife.inject(this);
        mContext = this;
        mActivity = this;
        initTitle();
        workList = new ArrayList<>();
        initData();
        EventBus.getDefault().register(this);
        workLabelPersenter = new RecruitPersenter(mContext, (RecruitConstant.WorkLabelView) mActivity);
        doWorkPersenter = new RecruitPersenter(mContext, (RecruitConstant.DoWorkView) mActivity);
        doWorkInfoPersenter = new RecruitPersenter(mContext, (RecruitConstant.DoWorkInfoView) mActivity);
        updateWorkerPersenter = new RecruitPersenter(mContext, (RecruitConstant.UpdateWorkerInfoView) mActivity);
        workLabelPersenter.getWorkLabel();
        initPopup();
        Intent intent = getIntent();
        userId = intent.getIntExtra(StringConstants.USERID, 0);
        type = intent.getStringExtra(StringConstants.DOWORKTYPE);
        if (isUpdate()) {
            doWorkInfoPersenter.getDoWorkInfo();
        }
    }

    boolean isUpdate() {
        return EmptyUtils.isNotEmpty(type) && type.equals(StringConstants.UPDATE);
    }

    private void initPopup() {
        popupSelectCoverage = new PopupWindow();
        View view = LayoutInflater.from(mContext).inflate(R.layout.popup_select_coverage_layout, null);
        popupSelectCoverage.setContentView(view);
        popupSelectCoverage.setWidth(DrawerLayout.LayoutParams.WRAP_CONTENT);
        popupSelectCoverage.setHeight(DrawerLayout.LayoutParams.WRAP_CONTENT);
//        alertPopupView.setTouchable(true);
        popupSelectCoverage.setFocusable(false);
        popupSelectCoverage.setBackgroundDrawable(new ColorDrawable(0x00000000));
        btn_cannel = view.findViewById(R.id.btn_cannel);
        btn_ok = view.findViewById(R.id.btn_ok);
        btn_cannel.setOnClickListener(this);
        btn_ok.setOnClickListener(this);
        recyConverage = view.findViewById(R.id.do_recy_popup_coverage_layout);
        labelList = new ArrayList<>();
        if (Constants.positions != null && Constants.positions.size() > 0) {
            List<String> converageList = Constants.positions;
            for (int i = 0; i < converageList.size(); i++) {
                WorkLabelBean labelbean = new WorkLabelBean();
                labelbean.setName(converageList.get(i));
                labelList.add(labelbean);
            }
        }
        adapter = new RetruitLabelAdapter(mContext, labelList);
        recyConverage.setLayoutManager(new FullyGridLayoutManager(mContext, 4));
        recyConverage.setAdapter(adapter);
    }

    private void initPublishParam() {
        doWorkParam = new RecruitDoWorkParam();
        doWorkParam.setId(Constants.userId);//用户ID
        doWorkParam.setIntroduce(doEtTitle.getText().toString());//描述
        doWorkParam.setCoverage(doServiceLocation.getText().toString());//服务区域
        if (EmptyUtils.isNotEmpty(Constants.bdLocation)) {
            doWorkParam.setLat(String.valueOf(Constants.bdLocation.getLatitude()));//纬度
            doWorkParam.setLog(String.valueOf(Constants.bdLocation.getLongitude()));//经度
        }
        doWorkParam.setFreetime(doTvBenginDate.getText().toString()
                + "," + doTvEndDate.getText().toString());
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < workList.size(); i++) {
            if (workList.get(i).isChecked()) {
                if (sb.length() > 0) {
                    sb.append(",");
                }
                sb.append(workList.get(i).getId());
            }
        }
        doWorkParam.setRole(sb.toString());
    }

    private void initData() {
        labelAdapter = new RetruitWorkLabelAdapter(mContext, workList);
        recyWorkLabel.setLayoutManager(new FullyGridLayoutManager(mContext, 4));
        recyWorkLabel.setAdapter(labelAdapter);
        doTvBenginDate.setText(TimeUtils.getNowString());
        doTvEndDate.setText(TimeUtils.getNowString());
    }

    @Override
    protected void setListener() {
        setCTitle("我要干活信息发布");
        setLeftOneBg(R.drawable.ic_back);
    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_cannel:
                //用户选择区域取消
                popupSelectCoverage.dismiss();
                break;
            case R.id.btn_ok:
//            用户选择区域确定
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < labelList.size(); i++) {
                    if (labelList.get(i).isChecked()) {
                        if (sb.length() > 0) {
                            sb.append(",");
                        }
                        sb.append(labelList.get(i).getName());
                    }
                }
                doServiceLocation.setText(sb.toString());
                popupSelectCoverage.dismiss();
                break;
            default:
                break;
        }
    }

    @OnClick({R.id.do_work_btn_pulish, R.id.do_service_location, R.id.do_tv_bengin_date, R.id.do_tv_end_date})
    public void Onclick(View v) {
        switch (v.getId()) {
            case R.id.do_work_btn_pulish:
                //我要干活信息发布
                if (isFromFull()) {
                    initPublishParam();
                    if (isUpdate()) {
                        updateWorkerPersenter.updateWorkerInfo();
                    } else {
                        doWorkPersenter.postDoWork();
                    }
                }
                break;
            case R.id.do_service_location:
                //选择区域服务
                popupSelectCoverage.showAtLocation(mCenterone, Gravity.CENTER, 0, 0);
                break;
            case R.id.do_tv_bengin_date:
                //选择开始时间
                showPickerView(doTvBenginDate);
                break;
            case R.id.do_tv_end_date:
                showPickerView(doTvEndDate);
                //选择结束时间
                break;
            default:
                break;
        }
    }

    public boolean isFromFull() {
        if (EmptyUtils.isEmpty(doEtTitle.getText().toString())) {
            Toast.makeText(mContext, "请输入描述信息", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (doServiceLocation.getText().toString().equals("请选择服务区域")) {
            Toast.makeText(mContext, "请选择服务区域", Toast.LENGTH_SHORT).show();
            return false;
        }
        boolean isLabel = false;
        for (int i = 0; i < workList.size(); i++) {
            if (workList.get(i).isChecked()) {
                isLabel = true;
                break;
            }

        }
        if (!isLabel) {
            Toast.makeText(mContext, "请至少选择一个工作标签", Toast.LENGTH_SHORT).show();
            return false;
        }
        return isLabel;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void unpdateList(WorkLabelMessage message) {
        workList = message.workLableList;
        labelAdapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void unpdateList(LabelMessage message) {
        labelList = message.workLableList;
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //    时间选择器
    void showPickerView(final TextView tv) {
        //时间选择器
        TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                tv.setText(DateUtils.getStringDate(date));
            }
        }).setType(new boolean[]{true, true, true, true, true, true})
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。

        pvTime.show();
    }

    @Override
    public void setData(Object o) {
        workList.clear();
        List<WorkLabelBean> lableBean = (List<WorkLabelBean>) o;
        workList.addAll(lableBean);
        labelAdapter.notifyDataSetChanged();
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void message(String str) {

    }

    @Override
    public RecruitDoWorkParam postDoWork() {
        return doWorkParam;
    }

    @Override
    public void publishDoWork() {
        Toast.makeText(mContext, "发布成功", Toast.LENGTH_SHORT).show();
        this.finish();
    }

    @Override
    public void getWorkLabel() {

    }

    @Override
    public int getDoWorkInfo() {
        return userId;
    }

    @Override
    public void getDoworkSuccess(Object o) {
        List<DoWorkInfoBean> doWorkInfoList = (List<DoWorkInfoBean>) o;
        if (doWorkInfoList.size() > 0) {
            DoWorkInfoBean infoBean = doWorkInfoList.get(0);
            doEtTitle.setText(infoBean.getIntroduce());//标题
            doServiceLocation.setText(infoBean.getCoverage());//服务区域
            String[] label = infoBean.getRole().split(",");
            for (int i = 0; i < label.length; i++) {
                Integer integer = Integer.valueOf(label[i]);
                labelList.get(integer).setChecked(true);
            }
            labelAdapter.notifyDataSetChanged();
            String[] split = infoBean.getFreetime().split(",");
            doTvBenginDate.setText(split[0]);//开始时间
            doTvEndDate.setText(split[1]);//结束时间
        }
    }

    @Override
    public RecruitDoWorkParam updateWorkerInfo() {
        return doWorkParam;
    }

    @Override
    public void updateSuccess() {
        Toast.makeText(mContext, "更新成功", Toast.LENGTH_SHORT).show();
        RefreshMessage refreshMessage = new RefreshMessage();
        EventBus.getDefault().post(refreshMessage);
        mActivity.finish();
    }

}
